import { Form, Table, message } from 'antd';
import { ContractManageAPI } from '../common/type';
import Cls from 'classnames';
import { getFieldConfig } from '../mconfig';
import { useContext, useEffect, useMemo, useState } from 'react';
import { getKeyRouter, getTenantID } from '@/utils';
import { ConractControllerContext, IContractsActionEnum } from '../common';
import { ILoadMapTypeAll } from '@/common';

import { getBaseUrl } from '@/services/urlconst';
import { OpenAttachModal } from './OpenAttachModal';

export const UpdateFiledTableView: React.FC<ContractManageAPI.IUpdateFiledTableView> = ({ formName, loadMapInfo, onFormChange }) => {
  /** 获取上下文 */
  const { pageType, contractForm, contarctJsonList, contractDispatch, readReadShowFileRun, updteAddOrEdit, contractDetailInfo, getDetailInfoRun, curRes } =
    useContext(ConractControllerContext);

  /** 保存附件数据 */
  const [fileddDataSource, setFiledDataSource] = useState<Record<string, any>[]>([]);

  /** 打开新增附件弹窗 */
  const [openAddAttachModal, setOpenAddAttachModal] = useState<boolean>(false);

  /** 初始化 */
  useEffect(() => {
    formName?.setFieldsValue({
      attachList: fileddDataSource,
    });
  }, [fileddDataSource]);

  // /** 详情初始化 */
  // useEffect(() => {
  //   if (contractDetailInfo?.id) {
  //     const attachList: Record<string, any>[] = contractDetailInfo?.attachList ? contractDetailInfo?.attachList : [];
  //     setFiledDataSource(attachList);
  //   }
  // }, [contractDetailInfo?.attachList?.length]);

  /** 添加附件回调 */
  const addFiledCallback = () => {
    const addItemObj: Record<string, any> = {
      key: `filedTable-${getKeyRouter()}`,
      modifyFlag: 0,
    };
    let changeList: Record<string, any>[] = contarctJsonList?.['attachList']?.length > 0 ? contarctJsonList?.['attachList'] : [];
    changeList?.push(addItemObj);
    contractDispatch({
      type: IContractsActionEnum.CONTRACT_JSONLIST,
      payload: {
        ...contarctJsonList,
        attachList: changeList,
      },
    });

    setFiledDataSource((prevState: Record<string, any>[]) => {
      const nowFiledTable: Record<string, any>[] = formName?.getFieldValue('attachList')?.length > 0 ? formName?.getFieldValue('attachList') : [];
      let newFiledList: Record<string, any>[] = [...nowFiledTable];
      newFiledList?.push(addItemObj);
      return newFiledList;
    });
  };

  /** 删除附件 */
  const delFiledCallback = (resObj: Record<string, any>) => {
    let attachList = contractForm?.getFieldValue('attachList');
    let arr = attachList?.filter((item) => item?.attachType == `${getTenantID()}${ILoadMapTypeAll.CONTRACT_FIELDTYPE}1007`);

    /**已填写授权代表至少保留一个相关附件 */
    if (arr?.length < 2) {
      let authName = formName?.getFieldValue('authName');
      if (resObj?.attachType == `${getTenantID()}${ILoadMapTypeAll.CONTRACT_FIELDTYPE}1007` && authName && authName != '无') {
        return message.error('已填写授权代表，至少保留一个该类型附件');
      }
    }

    let newChangeList: Record<string, any>[] = [];
    const changeList: Record<string, any>[] = contarctJsonList?.['attachList']?.length > 0 ? contarctJsonList?.['attachList'] : [];
    if (resObj && resObj?.id) {
      let delObj: Record<string, any> = {
        ...resObj,
        modifyFlag: '2',
      };
      newChangeList = changeList?.filter((item: any) => item?.id != delObj?.id);
      newChangeList?.push(delObj);
    } else if (resObj && resObj?.key) {
      newChangeList = changeList?.filter((item: any) => item?.key != resObj?.key);
    }
    contractDispatch({
      type: IContractsActionEnum.CONTRACT_JSONLIST,
      payload: {
        ...contarctJsonList,
        attachList: newChangeList,
      },
    });

    setFiledDataSource((_prevState: Record<string, any>[]) => {
      const newAttachList: Record<string, any>[] = contractForm?.getFieldValue('attachList');
      const newFiledList: Record<string, any>[] = newAttachList?.filter((item: any) => {
        if (item?.id) {
          return item?.id != resObj?.id;
        } else {
          return item?.key != resObj?.key;
        }
      });
      return newFiledList;
    });
  };

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  /** 表格配置 */
  const columnsMemo = useMemo(() => {
    return getFieldConfig(
      contractForm,
      addFiledCallback,
      delFiledCallback,
      loadMapInfo,
      pageType,
      onFormChange,
      onOpenReadOfdWord,
      setOpenAddAttachModal,
      contractDetailInfo,
      curRes,
    );
  }, [fileddDataSource, contarctJsonList, contractForm, loadMapInfo, pageType]);

  return (
    <>
      <div className={Cls('list-table', 'descriptionsType-tableSty', 'descriptionsType-tableFormSty')}>
        <Form.Item name="attachList" valuePropName="dataSource">
          <Table
            bordered
            columns={columnsMemo}
            size="small"
            dataSource={fileddDataSource}
            rowKey={(res) => (res?.id ? res?.id : res?.key)}
            scroll={{ x: 1200, y: '' }}
            pagination={false}
          />
        </Form.Item>
      </div>

      {/* 详情中保存添加附件 */}
      {openAddAttachModal && (
        <OpenAttachModal
          prefixCls={''}
          onClose={() => {
            setOpenAddAttachModal(false);
          }}
          addContractAttachRun={updteAddOrEdit?.addContractAttachRun}
          contractDetailInfo={contractDetailInfo}
          reloadDetail={getDetailInfoRun}
          setFiledDataSource={setFiledDataSource}
          onOpenReadOfdWord={onOpenReadOfdWord}
        />
      )}
    </>
  );
};
